#coding=utf8
import requests
import time

class binance(object):

    def __init__(self):
        self.URL='https://api.binance.com/'


    def get_symbol_list(self,money_name='all'):#返回交易对列表
        r = requests.get(self.URL+'/api/v3/ticker/price')
        symbol=r.json()#获取所有交易对和价格字典列表
        sym_list=[]
        for s in symbol:
            if money_name!='all':
                if s['symbol'][-len(money_name):]==money_name:
                    sym_list.append(s['symbol'])
            else:
                sym_list.apped(s['symbol'])
        return sym_list

    def get_ticker_24hr_quoteVolume(self,symbol):
        params={'symbol':symbol}
        r = requests.get(self.URL+'/api/v1/ticker/24hr',params=params)
        return float(r.json()['quoteVolume'])


    def get_symbol_price(self,symbol):#返回指定交易对价格
        params={'symbol':symbol}
        r = requests.get(self.URL+'/api/v3/ticker/price',params=params)
        return float(r.json()['price'])

    def get_Klines(self,symbol,interval,limit=500):#返回K线数据
        params={'symbol':symbol,'interval':interval,'limit':limit}
        r = requests.get(self.URL+'/api/v1/klines', params=params)
        return symbol,r.json()#时间升序

    def get_MA(self,x,n,symbol_klines,multiple=1):#返回MA线值
        symbol=symbol_klines[0]
        klines=symbol_klines[1]
        sum_close_price=0
        if n==0:
            sum_close_price=self.get_symbol_price(symbol)
            for k in range(-1,-x,-1):
                sum_close_price+=float(klines[k][4])
        else:
            for k in range(-n,-x-n,-1):
                sum_close_price+=float(klines[k][4])

        return sum_close_price*multiple/x

    def get_max_min_price(self,symbol_klines):#返回指定交易对1小时的最高价和最低价
        symbol=symbol_klines[0]
        klines=symbol_klines[1]
        maxp=0
        minp=10000000
        maxt=mint=time.time();
        for k in klines:
            if maxp<float(k[2]):
                maxp=float(k[2])
                maxt=k[6]/1000
            if minp>float(k[3]):
                minp=float(k[3])
                mint=k[6]/1000
        return maxt,maxp,mint,minp
